<?php
namespace Budget\BudgetBundle\Services;

use Doctrine\ORM\EntityManager;
use Budget\BudgetBundle\Entity\FamilyMonth as EntityFamilyMonth;
use Budget\BudgetBundle\Entity\Family;

class FamilyMonth
{
    protected $entityManager;
    
    public function __construct(EntityManager $entityManager) 
    {
        $this->entityManager = $entityManager;
    }
    
    public function generateAmountLeft(EntityFamilyMonth $familyMonth = null)
    {
        if (is_null($familyMonth)) {
            return 0;
        }
        
        $totalExpensesVal = $this->entityManager
                ->getRepository('BudgetBudgetBundle:Expense')
                ->getExpensesSumForFamilyMonth($familyMonth); 
        
        $totalExpensesVal += $this->entityManager
                ->getRepository('BudgetBudgetBundle:Expense')
                ->getExpensesSumForFamilyMonth($familyMonth, true); 
        
        $totalIncome = $this->countIncomes($familyMonth);
        
        return $totalIncome - $totalExpensesVal;
    }
    
    public function countIncomes(EntityFamilyMonth $familyMonth)
    {
        return $this->entityManager->getRepository('BudgetBudgetBundle:Income')->getTotalSumForMonth($familyMonth);
    }
    
    public function getPeriodFinance(EntityFamilyMonth $familyMonth = null)
    {
        if (is_null($familyMonth)) {
            $msg = "( - )";
        } else {
            $msg = '(' . $familyMonth->getStart()->format('d.m') . ' - ' .
                    '' . $familyMonth->getEnd()->format('d.m') . ')';
        }
        
        return $msg;
    }


    /**
     * Returns the current month defined by the family
     *
     * @param Family $family
     * @return EntityFamilyMonth
     */
    public function getCurrentMonth(Family $family)
    {
        return $this->entityManager
            ->getRepository('BudgetBudgetBundle:FamilyMonth')
            ->findCurrentForFamily($family);
    }
}
